package com.ymh.shiro.web.dao.impl;

import com.ymh.shiro.web.dao.UserDao;
import com.ymh.shiro.web.vo.User;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by aivin on 2018/8/21.
 */
@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public User getUserByUserName(String username) {
        String sql = "select user_name, password from users where user_name = ? ";
        List<User> list = jdbcTemplate.query(sql, new String[]{username}, new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                User user = new User();
                user.setUsername(resultSet.getString("user_name"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }
        });
        System.out.println("list=" + list.size());
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public List<String> getRolesByUserName(String userName) {
        String roleSql = "select role_name from user_roles where user_name = ?";
        List<String> list = jdbcTemplate.query(roleSql, new String[]{userName}, new RowMapper<String>() {
            @Override
            public String mapRow(ResultSet resultSet, int i) throws SQLException {
                return resultSet.getString("role_name");
            }
        });
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list;
    }


    /**
     * @param userName
     * @return
     */
    @Override
    public List<String> getPermissionByUserName(String userName) {
        return null;
    }
}
